import React, { useEffect, useState } from 'react'
import { Table, Button, Popconfirm, Image } from 'antd';
import { getBannerList, deleteBannerImg } from '../../api/banner.js'


const Index = () => {
    const [ bannerList, setBannerList ] = useState([])
    const [ pageNum, setPageNum ] = useState(0)
    const [ pageize, setPageize ] = useState(10)
    const columns = [
        {
          title: '序号',
          dataIndex: 'num',
          render (text, record, index) {
            return <span>{ pageNum * pageize + index+1 }</span>
          }
        },
        {
          title: '图片',
          dataIndex: 'img',
          render (text, data, index) {
            return <Image height={150} src={data.img} alt="" />
          }
        },
        {
          title: '链接',
          dataIndex: 'link'
        },
        {
          title: '提示',
          dataIndex: 'alt'
        },
        {
          title: '操作',
          dataIndex: 'do',
          render (text, data, index) {
            return (
              <Popconfirm
                placement="topRight"
                title='确认要删除此项吗？'
                onConfirm={() => {
                    deleteBanner(data.bannerid)
                }}
                okText="确认"
                cancelText="取消"
                >
                <Button type="primary" danger>
                    删除
                </Button>
              </Popconfirm>
            )
          }
        }
    ]
    const deleteBanner = (bannerid) => { 
        deleteBannerImg({bannerid}).then( () => {
          getBannerList().then(res => {  // *******最后的异步操作
            setBannerList(res.data)
          })
        })
    }
    const addBanner = () => {
        window.location.href = '/#/banner/add'
    }
    const pageChange = (pagination, filters, sorter) => {
      console.log(pagination);
      setPageNum(pagination.current - 1)
      setPageize(pagination.pageSize)
    }
    useEffect( () => {
      getBannerList().then( res => {
        setBannerList(res.data)
        // getAdminData({})
      })
      
    }, [])
    return (
        <>
            <div className="add-btn">
                <Button type="primary" onClick={addBanner}>添加轮播图</Button>
            </div>
            <div style={{width: '100%'}}>
                <Table columns={columns} dataSource={bannerList} onChange={pageChange} size="middle"  scroll={{ y: 580 }} rowKey="bannerid" />
            </div>
        </>
    )
}

export default Index